﻿//
// Created by Grishul Eugeny
//
// See license in License.txt
//

using System;
using System.Windows.Forms;
using System.Linq;
using System.IO;
using NCommander.Core;
using NCommander.NodeProviders;
using System.Drawing;

namespace NCommander
{
	public partial class RegistryView : NodeView
	{
		public RegistryView()
		{
			InitializeComponent();

			NodeProvider = new RegistryProvider();
		}

		public override void OnProviderRefresh( object provider, EventArgs args )
		{
			if( NodeProvider != null )
			{
				try
				{
					_nodes.BeginUpdate();
					_nodes.Items.Clear();

					_nodes.LargeImageList = _icons;
					_nodes.SmallImageList = _icons;

					var nodes = NodeProvider.GetNodes();

					foreach( var registryKey in nodes.Where( x => x.Type == NodeType.Internal ) )
					{
						var result = new ListViewItem( "[" + Path.GetFileName( registryKey.Path ) + "]" );
						result.Tag = registryKey;
						result.ImageKey = "Key.ico";

						_nodes.Items.Add( result );
					}

					foreach( RegistryProvider.RegistryValueNode value in nodes.Where( x => x.Type == NodeType.External ) )
					{
						var result = new ListViewItem( Path.GetFileName( value.Path ) );
						result.Tag = value;

						if( value.Kind == Microsoft.Win32.RegistryValueKind.String )
							result.ImageKey = "String.ico";
						else
							result.ImageKey = "Numeric.ico";

						result.SubItems.Add( value.Value + "" );

						_nodes.Items.Add( result );
					}

					_recentDirectories.Text = NodeProvider.CurrentNode.Path;
					DirectoryNavigated();
				}
				finally
				{
					_nodes.EndUpdate();
				}
			}
		}

		private void _keyAction_Opening( object sender, System.ComponentModel.CancelEventArgs e )
		{
			e.Cancel = _nodes.SelectedItems.Count == 0;

			if( _nodes.SelectedItems.Count == 1 )
			{
				e.Cancel = _nodes.SelectedItems[0].Tag is RegistryProvider.RegistryValueNode;
			}
		}

		private void _keyAction_Opened( object sender, EventArgs e )
		{

		}

		private void _newKeyToolStripMenuItem_Click( object sender, EventArgs e )
		{
			( NodeProvider as RegistryProvider ).CreateSubKey();
		}

		private void _deleteKeyToolStripMenuItem_Click( object sender, EventArgs e )
		{
			( NodeProvider as RegistryProvider ).DeleteSubKey( _nodes.SelectedItems[0].Tag as Node );
		}

		private void renameToolStripMenuItem_Click( object sender, EventArgs e )
		{
			_nodes.SelectedItems[0].BeginEdit();
		}

		private void _nodes_AfterLabelEdit( object sender, LabelEditEventArgs e )
		{
			if( e.Label != null )
				( NodeProvider as RegistryProvider ).RenameSubKey( _nodes.Items[e.Item].Tag as Node, e.Label );
		}
	}
}
